import React, { Component } from 'react';
import qs from 'qs';
import autoBind from 'react-autobind';
import { Link, browserHistory } from 'dva/router';
import { List, InputItem, Checkbox, Button, Picker, Toast } from 'antd-mobile';
import RegionPicker from './RegionPicker';

import { createForm } from 'rc-form';
import { getUserId } from '../../../utils/utils'

// style
import styles from './index.css';
import IconfontStyle from '../../../assets/iconfont/iconfont.css';

class AddAddressBody extends Component {
	constructor(props) {
        super(props)
        autoBind(this)

        let urlParam = this.getParamFromUrl()
        this.state = {
        	regionData: null,
        	regionCols: 3,
            regionLabels: urlParam.userId ? urlParam.regionLabels : null,
        	regionValue: urlParam.userId ? urlParam.regionValue : [2, 52, 500],
            isDefault: urlParam.isDefault || '0'
        }
    }
    getParamFromUrl() {
        const { location } = this.props
        let searchParm = location.search.replace('?', '')
        searchParm = qs.parse(searchParm)
        searchParm.regionValue = [+searchParm.province, +searchParm.city, +searchParm.district]
        searchParm.regionLabels = [searchParm.provinceName, searchParm.cityName, searchParm.districtName]
        
        searchParm.isDefault = searchParm.isDefault
        return searchParm
    }
    onDefaultChange(e) {
        this.setState({
            isDefault: e.target.checked ? '1' : '0'
        })
    }
    checkParam(param) {
        if(!param.consignee) {
            Toast.fail("请输入收货人!", 1)
            return false
        }
        if(param.consignee.length > 6) {
            Toast.fail('收货人长度必须小于6个字符!')
            return false
        }
        if(!(/^[\u4e00-\u9fa5_a-zA-Z0-9]+$/.test(param.consignee))){ 
            Toast.fail("收货人包含非法字符!", 1)
            return false
        } 
        if(!(/^1[34578]\d{9}$/.test(param.mobile))){ 
            Toast.fail("手机号码有误，请重填!", 1)
            return false
        }  
        if(!param.province || !param.city || !param.district) {
            Toast.fail("请选择省份、城市和区县!", 1)
            return false
        } 
        
        if(!param.address) {
            Toast.fail("请输入详细地址!", 1)
            return false
        }
        return true
    }
    onSaveAddress() {
        const { dispatch, meyley } = this.props
        let urlParam = this.getParamFromUrl()

        let values = this.props.form.getFieldsValue()
        let param = {
            ...urlParam,
            userId: +getUserId(),
            isDefault: this.state.isDefault == '1' ? 1 : 0,
            province: String(this.state.regionValue[0]),
            city: String(this.state.regionValue[1]),
            district: String(this.state.regionValue[2]),
            ...values
        }
        param.mobile = param.mobile && param.mobile.replace(/\s/g, '')

        if(this.checkParam(param)) {
            if(urlParam.userId) {
                // update
                dispatch({
                    'type': 'address/modifyAddress',
                    'payload': param
                })    
            } else {
                // create
                dispatch({
                    'type': 'address/createAddress',
                    'payload': param
                })    
            }
        }
        
    }
    
    onClickRegion() {
    	const { address } = this.props
    	this.setState({
	        regionData: address.province,
            isShowRegion: true
	    });
    }
    onConfirmRegionPicker() {
        let result = []
        this.state.regionData.map(d => {
            if(d.value === this.state.regionValue[0]) {
                result.push(d.label) 
                d.children.map(dd => {
                    if(dd.value === this.state.regionValue[1]) {
                        result.push(dd.label)

                        dd.children.map(ddd => {
                            if(ddd.value === this.state.regionValue[2]) {
                                result.push(ddd.label)
                            }
                        })
                    }
                })
            }
        })
        this.setState({
            regionLabels: result,
            isShowRegion: false
        })
    }
    onPickerChange(val) {
    	const { dispatch } = this.props
    	if(val.length === 1) {
    		let regionData = [...this.state.regionData];
            // get second/third region
    		dispatch({
    			type: 'address/fetchRegion',
    			payload: {
    				regionId: val[0],
    				callback: (data) => {
    					data.map(d => {
    						d.value = d.regionId
    						d.label = d.regionName
    					})

    					dispatch({
    						type: 'address/fetchRegion',
    						payload: {
    							regionId: data[0].regionId,
    							callback: (thdata) => {
    								thdata.map(d => {
    									d.value = d.regionId
    									d.label = d.regionName
    								})

    								data[0].children = thdata

    								regionData.map(d => {
			    						if(d.value === val[0]) {
			    							d.children = data
			    						}
			    					})
			    					this.setState({
										regionData: regionData,
                                        regionValue: [val[0], data[0].regionId, data[0].children[0].regionId]
									})
    							}
    						}
    					})
    				}
    			}
    		})
    	} else if(val.length === 2) {
            // get third region.
    		let regionData = [...this.state.regionData];
    		dispatch({
    			type: 'address/fetchRegion',
    			payload: {
    				regionId: val[1],
    				callback: (data) => {
    					data.map(d => {
    						d.value = d.regionId
    						d.label = d.regionName
    					})
    					regionData.map(d => {
    						if(d.value === val[0]) {
    							d.children.map(dc => {
    								if(dc.value === val[1]) {
    									dc.children = data
    								}
    							})
    						}
    					})
    					this.setState({
							regionData: regionData,
                            regionValue: [val[0], val[1], data[0].regionId]
						})
    				}
    			}
    		})
    	}
        this.setState({
            regionValue: val
        })
    	
    }
	render() {
		const { getFieldProps } = this.props.form
        let urlParam = this.getParamFromUrl()

	 	return (
	 		<div className={`${styles["add-address-body"]} add-address-body`}>
	 			<List>
			      <InputItem
			      	{...getFieldProps('consignee', {
                        initialValue: urlParam.consignee
                    })}
			      	className={styles['add-address-body-input']}
			        placeholder="请输入姓名"
			      ><span className={styles['add-address-body-title']}>收货人</span></InputItem>
			      <InputItem
			        {...getFieldProps('mobile', {
                        initialValue: urlParam.mobile
                    })}
			        type="phone"
			        className={styles['add-address-body-input']}
			        placeholder="请输入手机号码"
			      ><span className={styles['add-address-body-title']}>手机号码</span></InputItem>


			      <RegionPicker
			          data={this.state.regionData}
                      isShow={this.state.isShowRegion}
                      onClose={() => this.setState({ isShowRegion : false })}
                      onConfirm={this.onConfirmRegionPicker}
			          value={this.state.regionValue}
			          cols={this.state.regionCols}
			          onPickerChange={this.onPickerChange}
			          extra={ this.state.regionLabels ? this.state.regionLabels.join(' / ') : '请选择省份、城市和区县' }
			          className={`add-address-body-pick ${this.state.regionLabels ? 'add-address-body-pick-select' : null}`}
			        >
			        	<List.Item arrow="down" onClick={this.onClickRegion}><span className={styles['add-address-body-title']}>所在地区</span></List.Item>
			        </RegionPicker>

			      <InputItem
			        {...getFieldProps('address', {
                        initialValue: urlParam.address
                    })}
			        className={styles['add-address-body-input']}
			        placeholder="请输入街道、小区、和门牌号"
			      ><span className={styles['add-address-body-title']}>详细地址</span></InputItem>

			      <div className={styles['add-address-body-default']}>
			      	<Checkbox checked={this.state.isDefault == '1' ? true : false} onChange={this.onDefaultChange}><span style={{marginLeft: '0.12rem', verticalAlign: 'middle', fontSize: '0.28rem'}}>默认地址</span></Checkbox>
			      </div>
			    </List>

			    <div className={styles['add-address-body-controller']}>
			    	<Button className="meyley-button-red" onClick={this.onSaveAddress}><span style={{color: '#fff'}}>保存并使用</span></Button>
			    </div>
	 		</div>
	  	);
	}
};

AddAddressBody.propTypes = {
};

export default createForm()(AddAddressBody)
 